<template>
  <u-popup :show="CheckIn.showModal.value" mode="center" :round="10">
    <view class="vbox popup-container">
      <view class="popup-header">
        <text>{{
          CheckIn.modalMode.value === "edit" ? "编辑签到" : "添加签到"
        }}</text>
        <view class="fill"></view>
        <u-icon
          name="close"
          @click="closeModal"
          size="18"
        ></u-icon>
      </view>
      <u-form :model="CheckIn.currentModel" ref="formRef">
        <u-form-item label="签到名称" prop="name">
          <u-input
            v-model="CheckIn.currentModel.name"
            placeholder="输入签到名称"
            border="surround"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="签到描述" prop="desc">
          <u-input
            v-model="CheckIn.currentModel.desc"
            placeholder="输入签到描述"
            border="surround"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="签到范围(米)" prop="radius">
          <u-input
            v-model.number="CheckIn.currentModel.radius"
            type="digit"
            placeholder="输入签到范围(米)"
            border="surround"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="截止时间" prop="endTime">
          <u-datetime-picker
            :show="showDateTimePicker"
            v-model="dateTimeValue"
            mode="datetime"
            @confirm="handleDateTimeConfirm"
            @cancel="showDateTimePicker = false"
          ></u-datetime-picker>
          <u-input
            :value="formatDateTime(CheckIn.currentModel.endTime)"
            placeholder="请选择截止时间"
            border="surround"
            @click="showDateTimePicker = true"
            readonly
          ></u-input>
        </u-form-item>

        <view class="button-group">
          <u-button
            type="default"
            @click="closeModal"
            class="cancel-btn"
          >取消</u-button>
          <u-button
            type="primary"
            @click="handleSubmit"
            class="submit-btn"
          >{{ CheckIn.modalMode.value === 'edit' ? '保存' : '添加' }}</u-button>
        </view>
      </u-form>
    </view>
  </u-popup>
</template>

<script setup>
import { ref, watch } from 'vue';
import CheckIn from "@/js/admin/checkin.js";

const formRef = ref(null);
const showDateTimePicker = ref(false);
const dateTimeValue = ref(Date.now());

// 监听截止时间变化，同步到datetime picker
watch(() => CheckIn.currentModel.endTime, (newVal) => {
  if (newVal) {
    try {
      dateTimeValue.value = new Date(newVal).getTime();
    } catch (e) {
      console.error('时间转换错误:', e);
      dateTimeValue.value = Date.now();
    }
  }
}, { immediate: true });

// 表单提交处理
const handleSubmit = async () => {
  if (!CheckIn.currentModel.name.trim()) {
    uni.showToast({ title: '请输入签到名称', icon: 'none' });
    return;
  }
  
  if (!CheckIn.currentModel.endTime) {
    uni.showToast({ title: '请选择截止时间', icon: 'none' });
    return;
  }
  
  // 确保 radius 是数字类型
  if (typeof CheckIn.currentModel.radius === 'string') {
    CheckIn.currentModel.radius = parseInt(CheckIn.currentModel.radius) || 100;
  }
  
  // 调用VMControl的提交方法
  await CheckIn.handleSubmit();
  closeModal();
};

// 关闭模态框并刷新数据
const closeModal = () => {
  CheckIn.closePopup();
  // 延迟刷新以确保模态框关闭后再刷新
  setTimeout(() => {
    uni.$emit('refreshCheckInPage');
  }, 300);
};

// 处理日期时间确认
const handleDateTimeConfirm = (e) => {
  // 确保我们设置的是有效的时间值
  if (e && e.value) {
    CheckIn.currentModel.endTime = new Date(e.value).toISOString();
  }
  showDateTimePicker.value = false;
};

// 格式化日期时间显示
const formatDateTime = (dateValue) => {
  // 检查 dateValue 是否有效
  if (!dateValue) return '';
  
  try {
    // 如果是字符串，尝试解析为日期对象
    const date = typeof dateValue === 'string' ? new Date(dateValue) : new Date(dateValue);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) return '';
    
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '';
  }
};
</script>

<style scoped>
.popup-container {
  padding: 20px;
  width: 85vw;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.button-group {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.cancel-btn, .submit-btn {
  flex: 1;
}
</style>